#include "stm32f10x_rcc.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_usart.h"
#include "uart.h"

void uart_init(void)
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);

    GPIO_InitTypeDef GPIO_InitStruct =
    {
        .GPIO_Speed = GPIO_Speed_50MHz
    };

    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOA, &GPIO_InitStruct);

    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOA, &GPIO_InitStruct);

    USART_InitTypeDef USART_InitStruct =
    {
        .USART_BaudRate = 115200,
        .USART_WordLength = USART_WordLength_8b,
        .USART_StopBits = USART_StopBits_1,
        .USART_Parity = USART_Parity_No,
        .USART_Mode = USART_Mode_Tx | USART_Mode_Rx,
        .USART_HardwareFlowControl = USART_HardwareFlowControl_None
    };
    USART_Init(USART1, &USART_InitStruct);
    USART_Cmd(USART1, ENABLE);
}

char uart_recv_char(void)
{
    while (!USART_GetFlagStatus(USART1, USART_FLAG_RXNE));
    return USART_ReceiveData(USART1);
}

void uart_send_char(char c)
{
    USART_SendData(USART1, c);
    while (!USART_GetFlagStatus(USART1, USART_FLAG_TXE));
}

void uart_recv_line(char * buf, int len)
{
    int i = 0;
    while (i < len - 1)
    {
        char c = uart_recv_char();
        if (c == '\n') break;
        buf[i] = c;
        i++;
    }
    buf[i] = '\0';
}

void uart_send_line(const char * str)
{
    while (*str) uart_send_char(*str++);
    uart_send_char('\n');
}
